//
//  DrawEcgAnno.m
//  Ikinloop-demo
//
//  Created by Li Shen on 2021/4/23.
//  Copyright © 2021 lyh. All rights reserved.
//

#import "DrawEcgAnno.h"
#import "DrawUtils.h"
#import "ECGStateItem.h"

@interface DrawEcgAnno()

@property (nonatomic, strong) CALayer *layer;
@property (nonatomic, assign) CGContextRef context;

@property (nonatomic) NSInteger drawPointNum;
@property (nonatomic) NSInteger drawLineNum;
@property (nonatomic) CGFloat dataStartX;
@property (nonatomic) CGFloat dataStartY;
@property (nonatomic) CGFloat lastStartX;
@property (nonatomic) CGFloat lastStartY;
@property (nonatomic) NSInteger mmPixels;
@property (nonatomic) CGFloat width;
@property (nonatomic) CGFloat height;

@property (nonatomic) CGFloat xStepPixelPerPoint;
@property (nonatomic) CGFloat yStepPixelPerUv;


@property (nonatomic, strong) NSMutableArray<ECGStatePos*> *ecgStatePosArr;
@property (nonatomic, strong) DrawUtils *drawUils;

@property (nonatomic, strong) CAShapeLayer *shapelayer;
//贝塞尔曲线路径
@property (nonatomic, strong)UIBezierPath *bezierpath;

@property (nonatomic, strong) NSArray *ecgDatas;
@property (nonatomic, strong) NSArray *ecgStates;
@property (nonatomic, strong) NSMutableArray<CAShapeLayer*> *stateLayers;
@property (nonatomic, strong) CAShapeLayer *popLayer;
@end

@implementation DrawEcgAnno
- (instancetype)initWithLayer:(CALayer*)layer
{
    self = [super init];
    if (self) {
        self.layer = layer;
        [self setupDefaultValues];
    }
    
    return self;
}

- (instancetype)initWithLayer:(CALayer*)layer context:(CGContextRef)context{
    self = [super init];
    if (self) {
        self.layer = layer;
        self.context = context;
        [self setupDefaultValues];
    }
    
    return self;
}

- (void)setupDefaultValues{
    self.drawUils = [[DrawUtils alloc] initWithLayer:self.layer context:self.context];
    self.mmPixels = [DrawUtils mm2pt:1.0];
    self.ecgGain = 10;
    self.ecgSpeed = 25;
    self.sampleRate = 512;
    self.lineWidth = 1;
    self.dataStartX = 0;
    self.dataStartY =  4 * 5 * self.mmPixels;
    
    self.lastStartX = 0;
    self.lastStartY = 0;
    
    self.width = self.layer.frame.size.width;
    self.height = self.layer.frame.size.height;
    
    self.xStepPixelPerPoint = (_ecgSpeed / _sampleRate) * _mmPixels;
    self.yStepPixelPerUv = (_ecgGain * _mmPixels) / 1000;
    self.bezierpath = [[UIBezierPath alloc] init];
    self.shapelayer = [[CAShapeLayer alloc] init];
    self.stateLayers = [[NSMutableArray alloc] init];
    self.ecgStatePosArr = [[NSMutableArray alloc] init];
    self.popLayer = [[CAShapeLayer alloc] init];
    self.ecgstateOptions = [ECGStateItem getDefaultEcgStateOption];
}

- (void)resetStateBeforeDraw{
    [self.bezierpath removeAllPoints];
    [self.stateLayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    [self.stateLayers removeAllObjects];
    [self.ecgStatePosArr removeAllObjects];
    [self.popLayer removeFromSuperlayer];
    _drawPointNum = 0;
    
}

- (void)reload{
    self.width = self.layer.frame.size.width;
    self.height = self.layer.frame.size.height;
    self.dataStartX = 0;
    self.lastStartX = 0;
    self.lastStartY = 0;
    
}

- (void)drawLineEcg:(NSArray*)ecgdatas ecgStates:(NSArray*)ecgStates{
    CGFloat xStepPixelPerPoint = self.xStepPixelPerPoint;
    CGFloat yStepPixelPerUv = self.yStepPixelPerUv;
   
    CGFloat lastStartX = _dataStartX;
    CGFloat lastStartY = _dataStartY;
    [self resetStateBeforeDraw];
    for (int i = 0; i < ecgdatas.count; i++) {
        int value = ((NSNumber*)ecgdatas[i]).intValue;
        int state = ((NSNumber*)ecgStates[i]).intValue;
        
        //若大于画布宽度时,不画
        CGFloat pointX = _dataStartX + (_drawPointNum * xStepPixelPerPoint);
        if(pointX >= self.width){
            break;
        }
        [self.bezierpath moveToPoint:CGPointMake(lastStartX, lastStartY)];
        
        CGFloat x = _dataStartX + _drawPointNum * xStepPixelPerPoint;
        CGFloat y = _dataStartY - (value * yStepPixelPerUv);
        [self.drawUils addLineToBezierpath:self.bezierpath toEndPoint:CGPointMake(x, y) withLineWidth:_lineWidth];
        
        lastStartX = x;
        lastStartY = y;
        ECGStateItem *item = [self findEcgStateItem:state];
        if(item != nil){
            ECGStatePos *pos = [ECGStatePos new];
            pos.item = item;
            pos.point = CGPointMake(x, y);
            [self.ecgStatePosArr addObject:pos];
            [self drawEcgStateItem:item xPostion:x];
        }
        _drawPointNum++;
    }
    [self.drawUils addShapelayer:self.shapelayer withBezierpath:self.bezierpath withColor:self.ecgColor];
}

- (ECGStateItem*)findEcgStateItem:(int)state{
    if(self.ecgstateOptions == nil || self.ecgstateOptions.count <= 0){
        return nil;
    }
    for (ECGStateItem *item in self.ecgstateOptions) {
        if(item.state == state){
            return item;
        }
    }
    return nil;
}

- (void)drawEcgStateItem:(ECGStateItem *)item xPostion:(int)x{
    CGFloat height = [DrawUtils mm2pt:3];
    CGFloat width = [DrawUtils mm2pt:0.8];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(x, self.height-height , width, height)];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.fillColor = item.color.CGColor;
    [self.layer addSublayer:layer];
    [self.stateLayers addObject:layer];
}

- (void)getEcgStateByXY:(CGPoint)point{
    if(self.ecgStatePosArr == nil || self.ecgStatePosArr.count <= 0){
        return;
    }
    for (ECGStatePos *pos in self.ecgStatePosArr) {
        if(point.x >= pos.point.x - 10 && point.x <= pos.point.x + 10 ){
            [self drawEcgStateLabel:pos];
        }
    }
}

- (void)drawEcgStateLabel1:(ECGStatePos*)pos{
    CATextLayer *textLayer = [[CATextLayer alloc] init];
    [textLayer setAlignmentMode:kCAAlignmentCenter];
    [textLayer setBackgroundColor:[UIColor redColor].CGColor];
    
    [textLayer setString:pos.item.content];
    [textLayer setFrame:CGRectMake(0, 0, 100, 30)];
    [textLayer setPosition:CGPointMake(pos.point.x, 100)];
    textLayer.contentsScale = [UIScreen mainScreen].scale;
    [self.layer addSublayer:textLayer];
}

- (void)drawEcgStateLabel:(ECGStatePos*)pos{
    [self.popLayer removeFromSuperlayer];
    CGFloat height = [DrawUtils mm2pt:4];
    CGFloat width = [DrawUtils mm2pt:12];
    int oriy = (pos.point.y < 40 ? self.height/2 : pos.point.y);
    int y =  oriy - height;
    int x = pos.point.x - width/2;
    
    CGFloat angle = 10;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(x, y)];
    [path addLineToPoint:CGPointMake(x+ width,y)];
    [path addLineToPoint:CGPointMake(x + width, y+height)];
    [path addLineToPoint:CGPointMake(x + width/2+angle, y+height)];
    [path addLineToPoint:CGPointMake(x+width/2, y+height+angle)];
    [path addLineToPoint:CGPointMake(x+width/2-angle, y+height)];
    [path addLineToPoint:CGPointMake(x, y+height)];
    
    
    [path closePath];
    
    CATextLayer *textlayer = [CATextLayer layer];
    [textlayer setAlignmentMode:kCAAlignmentCenter];
    [textlayer setBackgroundColor:[UIColor clearColor].CGColor];
    textlayer.string = pos.item.content;
    textlayer.frame = CGRectMake(0, 0 , width, height);
    textlayer.position = CGPointMake(pos.point.x, oriy - height/2);
    textlayer.contentsScale = [UIScreen mainScreen].scale;
    textlayer.fontSize = 21;
    CAShapeLayer *shaperLayer = [CAShapeLayer layer];
    shaperLayer.path = path.CGPath;
    
    shaperLayer.fillColor = [UIColor grayColor].CGColor;
    [shaperLayer addSublayer:textlayer];
    self.popLayer = shaperLayer;
    [self.layer addSublayer:shaperLayer];
}

- (CGFloat)getxStepPixelPerPoint{
    return  _xStepPixelPerPoint;
}

- (int)getPointMaxNumPerScreen{
    CGFloat width = self.width;
    CGFloat xStep = [self getxStepPixelPerPoint];
    CGFloat linePointNum = (int)(width / xStep);
    return linePointNum;
}


@end
